<template>
  <el-dialog
    :model-value="modelValue"
    width="1200px"
    @close="handleClose"
    class="unified-dialog config-edit-dialog"
    :close-on-click-modal="false"
  >
    <template #header>
      <DialogHeader 
        :icon="isEdit ? 'Edit' : 'Plus'"
        :title="isEdit ? '编辑配置' : '新增配置'"
        :description="isEdit ? '修改 StarRocks 集群监控配置' : '添加新的 StarRocks 集群监控配置'"
        :type="isEdit ? 'warning' : 'success'"
      />
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="140px"
      label-position="left"
    >
      <el-tabs v-model="activeTab" class="config-tabs">
        <!-- Tab 1: 基础信息 -->
        <el-tab-pane label="基础信息" name="basic">
          <div class="tab-content">
            <el-form-item label="集群标识" prop="cluster_tag">
              <el-input
                v-model="formData.cluster_tag"
                placeholder="请输入集群标识（如：etl, api）"
                :disabled="isEdit"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="配置名称" prop="config_name">
              <el-input
                v-model="formData.config_name"
                placeholder="请输入配置名称"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="配置描述" prop="config_desc">
              <el-input
                v-model="formData.config_desc"
                type="textarea"
                :rows="2"
                placeholder="请输入配置描述"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-tab-pane>

        <!-- Tab 2: 节点配置 -->
        <el-tab-pane label="节点配置" name="nodes">
          <div class="tab-content">
            <el-form-item label="FE主节点地址" prop="fe_master_node">
              <el-input v-model="formData.fe_master_node" placeholder="请输入FE主节点IP地址" />
            </el-form-item>
            
            <el-form-item label="是否有FE从节点">
              <el-switch v-model="formData.has_fe_slaves" :active-value="1" :inactive-value="0" />
            </el-form-item>
            
            <el-form-item label="FE从节点列表" prop="fe_slave_nodes">
              <el-input
                v-model="formData.fe_slave_nodes"
                type="textarea"
                :rows="2"
                placeholder="多个IP地址用逗号分隔，如：10.1.1.101,10.1.1.102"
              />
            </el-form-item>
            
            <el-form-item label="BE节点列表" prop="be_nodes">
              <el-input
                v-model="formData.be_nodes"
                type="textarea"
                :rows="2"
                placeholder="多个IP地址用逗号分隔，如：10.1.1.61,10.1.1.62,10.1.1.63"
              />
            </el-form-item>
          </div>
        </el-tab-pane>

        <!-- Tab 3: 端口配置 -->
        <el-tab-pane label="端口配置" name="ports">
          <div class="tab-content">
            <el-form-item label="监控端口" prop="metrics_port">
              <el-input-number v-model="formData.metrics_port" :min="1" :max="65535" />
            </el-form-item>
            
            <el-form-item label="FE HTTP端口" prop="fe_http_port">
              <el-input-number v-model="formData.fe_http_port" :min="1" :max="65535" />
            </el-form-item>
            
            <el-form-item label="BE HTTP端口" prop="be_http_port">
              <el-input-number v-model="formData.be_http_port" :min="1" :max="65535" />
            </el-form-item>
            
            <el-form-item label="FE日志端口" prop="fe_log_port">
              <el-input-number v-model="formData.fe_log_port" :min="1" :max="65535" />
            </el-form-item>
          </div>
        </el-tab-pane>

        <!-- Tab 4: StarRocks配置 -->
        <el-tab-pane label="StarRocks配置" name="starrocks">
          <div class="tab-content">
            <el-form-item label="安装目录" prop="starrocks_home">
              <el-input v-model="formData.starrocks_home" placeholder="/opt/datasophon/StarRocks-3.3.16" />
            </el-form-item>
            
            <el-form-item label="控制脚本路径">
              <el-input v-model="formData.control_script" placeholder="如：{starrocks_home}/control_starrocks.sh" />
            </el-form-item>
            
            <el-form-item label="运行用户">
              <el-input v-model="formData.starrocks_user" placeholder="starrocks" />
            </el-form-item>
            
            <el-form-item label="FE日志目录">
              <el-input v-model="formData.fe_log_dir" placeholder="默认：{starrocks_home}/fe/log" />
            </el-form-item>
            
            <el-form-item label="BE日志目录">
              <el-input v-model="formData.be_log_dir" placeholder="默认：{starrocks_home}/be/log" />
            </el-form-item>
            
            <el-form-item label="日志备份目录">
              <el-input v-model="formData.log_backup_dir" placeholder="/opt/starrocks_log_backup" />
            </el-form-item>
            
            <el-form-item label="日志保留天数">
              <el-input-number v-model="formData.log_keep_days" :min="1" :max="365" />
            </el-form-item>
            
            <el-form-item label="备份日志保留天数">
              <el-input-number v-model="formData.log_backup_days" :min="1" :max="365" />
            </el-form-item>
          </div>
        </el-tab-pane>

        <!-- Tab 5: Prometheus配置 -->
        <el-tab-pane label="Prometheus配置" name="prometheus">
          <div class="tab-content">
            <el-form-item label="启用Prometheus">
              <el-switch v-model="formData.enable_prometheus" :active-value="1" :inactive-value="0" />
            </el-form-item>
            
            <el-form-item label="Prometheus服务地址">
              <el-input 
                v-model="formData.prometheus_url" 
                placeholder="http://10.1.1.28:9090"
              />
            </el-form-item>
            
            <el-form-item label="FE节点查询语句">
              <el-input
                v-model="formData.fe_query"
                type="textarea"
                :rows="2"
                placeholder='如：up{job="StarRocks_Cluster01", group="fe"}'
              />
            </el-form-item>
            
            <el-form-item label="BE节点查询语句">
              <el-input
                v-model="formData.be_query"
                type="textarea"
                :rows="2"
                placeholder='如：up{job="StarRocks_Cluster01", group="be"}'
              />
            </el-form-item>
            
            <el-form-item label="失败处理策略">
              <el-switch 
                v-model="formData.prometheus_required" 
                :active-value="1" 
                :inactive-value="0"
                active-text="必需"
                inactive-text="可选"
              />
            </el-form-item>
          </div>
        </el-tab-pane>

        <!-- Tab 6: 告警与重启 -->
        <el-tab-pane label="告警与重启" name="alert">
          <div class="tab-content">
            <!-- 告警配置 -->
            <div class="section-title">告警配置</div>
            
            <el-form-item label="启用告警">
              <el-switch v-model="formData.is_alert" :active-value="1" :inactive-value="0" />
            </el-form-item>
            
            <el-form-item label="Webhook地址">
              <el-input
                v-model="formData.webhook_url"
                placeholder="企业微信机器人Webhook地址"
                type="textarea"
                :rows="2"
              />
            </el-form-item>
            
            <el-form-item label="告警间隔时间(秒)">
              <el-input-number v-model="formData.alert_interval" :min="60" :max="86400" :step="60" />
            </el-form-item>
            
            <el-form-item label="最大告警次数">
              <el-input-number v-model="formData.max_alert_count" :min="1" :max="10" />
            </el-form-item>

            <!-- 重启配置 -->
            <div class="section-title" style="margin-top: 24px;">重启配置</div>
            
            <el-form-item label="启用自动重启">
              <el-switch v-model="formData.is_restart" :active-value="1" :inactive-value="0" />
            </el-form-item>
            
            <el-form-item label="最大重启次数">
              <el-input-number v-model="formData.max_restart_count" :min="1" :max="10" />
            </el-form-item>
            
            <el-form-item label="重启超时时间(秒)">
              <el-input-number v-model="formData.restart_timeout" :min="30" :max="600" :step="30" />
            </el-form-item>

            <!-- SSH配置 -->
            <div class="section-title" style="margin-top: 24px;">SSH配置</div>
            
            <el-form-item label="SSH用户">
              <el-input v-model="formData.ssh_user" placeholder="root" />
            </el-form-item>
            
            <el-form-item label="SSH超时时间(秒)">
              <el-input-number v-model="formData.ssh_timeout" :min="5" :max="300" :step="5" />
            </el-form-item>

            <!-- 监控状态 -->
            <div class="section-title" style="margin-top: 24px;">监控状态</div>
            
            <el-form-item label="启用监控">
              <el-switch v-model="formData.is_monitor" :active-value="1" :inactive-value="0" />
              <div class="form-item-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>状态将根据监控、告警、自动重启开关自动计算</span>
              </div>
            </el-form-item>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ submitting ? '提交中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import DialogHeader from '@/components/DialogHeader.vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('ConfigEditDialog')
const props = defineProps({
  modelValue: Boolean,
  config: Object,
  isEdit: Boolean
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref(null)
const submitting = ref(false)
const activeTab = ref('basic')

const formData = reactive({
  cluster_tag: '',
  config_name: '',
  config_desc: '',
  fe_master_node: '',
  fe_slave_nodes: '',
  has_fe_slaves: 1,
  be_nodes: '',
  metrics_port: 9010,
  fe_http_port: 8060,
  be_http_port: 8071,
  fe_log_port: 9010,
  starrocks_home: '/opt/datasophon/StarRocks-3.3.16',
  control_script: '',
  starrocks_user: 'starrocks',
  fe_log_dir: '',
  be_log_dir: '',
  log_backup_dir: '/opt/starrocks_log_backup',
  log_keep_days: 2,
  log_backup_days: 7,
  prometheus_url: '',
  fe_query: '',
  be_query: '',
  enable_prometheus: 1,
  prometheus_required: 0,
  webhook_url: '',
  is_alert: 1,
  alert_interval: 360,
  max_alert_count: 3,
  is_restart: 1,
  max_restart_count: 3,
  restart_timeout: 120,
  ssh_user: 'root',
  ssh_timeout: 30,
  is_monitor: 1,
  status: 'enAll'
})

const rules = {
  cluster_tag: [
    { required: true, message: '请输入集群标识', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '仅支持字母、数字、下划线和横线', trigger: 'blur' }
  ],
  config_name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  fe_master_node: [
    { required: true, message: '请输入FE主节点地址', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: 'IP地址格式不正确', trigger: 'blur' }
  ],
  be_nodes: [
    { required: true, message: '请输入BE节点列表', trigger: 'blur' }
  ],
  metrics_port: [
    { type: 'number', min: 1, max: 65535, message: '端口范围1-65535', trigger: 'blur' }
  ],
  fe_http_port: [
    { type: 'number', min: 1, max: 65535, message: '端口范围1-65535', trigger: 'blur' }
  ],
  be_http_port: [
    { type: 'number', min: 1, max: 65535, message: '端口范围1-65535', trigger: 'blur' }
  ],
  fe_log_port: [
    { type: 'number', min: 1, max: 65535, message: '端口范围1-65535', trigger: 'blur' }
  ]
}

// 定义 resetForm 函数 - 必须在 watch 之前定义，因为 watch 使用了 immediate: true
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重置为默认值
  Object.assign(formData, {
    cluster_tag: '',
    config_name: '',
    config_desc: '',
    fe_master_node: '',
    fe_slave_nodes: '',
    has_fe_slaves: 1,
    be_nodes: '',
    metrics_port: 9010,
    fe_http_port: 8060,
    be_http_port: 8071,
    fe_log_port: 9010,
    starrocks_home: '/opt/datasophon/StarRocks-3.3.16',
    control_script: '',
    starrocks_user: 'starrocks',
    fe_log_dir: '',
    be_log_dir: '',
    log_backup_dir: '/opt/starrocks_log_backup',
    log_keep_days: 2,
    log_backup_days: 7,
    prometheus_url: '',
    fe_query: '',
    be_query: '',
    enable_prometheus: 1,
    prometheus_required: 0,
    webhook_url: '',
    is_alert: 1,
    alert_interval: 360,
    max_alert_count: 3,
    is_restart: 1,
    max_restart_count: 3,
    restart_timeout: 120,
    ssh_user: 'root',
    ssh_timeout: 30,
    is_monitor: 1,
    status: 'enAll'
  })
  // 重置 activeTab
  activeTab.value = 'basic'
}

watch(() => props.config, (newConfig) => {
  if (newConfig) {
    componentLogger.info('ConfigEditDialog - 接收到配置数据', {
      hasConfig: !!newConfig,
      prometheus_url: newConfig.prometheus_url,
      fe_query: newConfig.fe_query,
      be_query: newConfig.be_query,
      enable_prometheus: newConfig.enable_prometheus
    })
    
    // 编辑模式，先重置表单，再填充数据
    resetForm()
    
    // 填充表单数据（包括 null 值，确保清空旧数据）
    Object.keys(formData).forEach(key => {
      if (newConfig[key] !== undefined) {
        formData[key] = newConfig[key]
      }
    })
    
    componentLogger.info('ConfigEditDialog - formData填充完成', {
      prometheus_url: formData.prometheus_url,
      fe_query: formData.fe_query,
      be_query: formData.be_query,
      enable_prometheus: formData.enable_prometheus
    })
  } else {
    // 新增模式，重置表单
    resetForm()
  }
}, { immediate: true })

const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const url = props.isEdit
      ? `/starrocks-cluster-monitor/configs/${props.config.id}`
      : '/starrocks-cluster-monitor/configs'
    
    const method = props.isEdit ? 'put' : 'post'
    
    // 移除 status 字段，让后端根据开关状态自动计算
    const { status, ...submitData } = formData
    
    const response = await api[method](url, submitData)
    
    if (response.data.success) {
      ElMessage.success(props.isEdit ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    }
  } catch (error) {
    if (error.errors) {
      // 表单验证失败
      componentLogger.warn('表单验证失败', error)
    } else {
      componentLogger.error('提交配置失败', error)
      ElMessage.error('提交失败')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
/* Tab 样式 */
.config-tabs {
  margin-top: -10px;
}

.config-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
  border-bottom: 2px solid #e4e7ed;
}

.config-tabs :deep(.el-tabs__nav-wrap) {
  padding-left: 10px;
}

.config-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
  padding: 0 24px;
  height: 44px;
  line-height: 44px;
}

.config-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

.config-tabs :deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 3px;
}

.tab-content {
  padding: 10px 0;
  min-height: 400px;
  max-height: 500px;
  overflow-y: auto;
}

.tab-content::-webkit-scrollbar {
  width: 6px;
}

.tab-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

/* 分组标题 */
.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 100%;
}

/* 适配加宽后的对话框 */
.config-edit-dialog :deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
}

.config-edit-dialog :deep(.el-form-item__content) {
  line-height: 32px;
}

/* 表单提示样式 */
.form-item-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f4f4f5;
  border-radius: 6px;
  font-size: 13px;
  color: #606266;
}

.form-item-tip .el-icon {
  color: #909399;
  font-size: 14px;
}
</style>
